import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_theme.dart';
import 'dart:async';
import 'package:gitcode_pocket_tool/core/app_config.dart';

class RepositoriesPage extends StatefulWidget {
  const RepositoriesPage({super.key});

  @override
  State<RepositoriesPage> createState() => _RepositoriesPageState();
}

class _RepositoriesPageState extends State<RepositoriesPage> {
  final GitCodeApiClient _apiClient = GitCodeApiClient();
  List<GitCodeRepository> _repositories = [];
  bool _isLoading = false;
  String? _errorMessage;
  int _currentPage = 1;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadRepositories();
  }

  Future<void> _loadRepositories() async {
    if (_isLoading || (!_hasMore && _currentPage > 1)) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 使用新的API方法获取gitcode用户的仓库列表
      final newRepositories = await _apiClient.getUserRepositories(
        username: 'gitcode', // 获取gitcode官方用户的仓库
        personalToken: AppConfig.demoToken,
        sort: 'updated',
        direction: 'desc',
        perPage: 10,
        page: _currentPage,
      );

      setState(() {
        if (_currentPage == 1) {
          _repositories = newRepositories;
        } else {
          _repositories.addAll(newRepositories);
        }

        // 如果没有更多数据了，设置_hasMore为false
        _hasMore = newRepositories.length == 10;
        _currentPage++;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget _buildRepositoryItem(GitCodeRepository repo) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: const Color(0x1A4361EE),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(Icons.code,
                      size: 24, color: AppTheme.primaryColor),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    '仓库名称',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            if (repo.description != null) ...[
              Text(
                repo.description!,
                style: TextStyle(color: AppTheme.textSecondary),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
            ],
            Row(
              children: [
                const Icon(Icons.star, size: 16, color: Colors.amber),
                const SizedBox(width: 4),
                Text(
                  '${repo.stars ?? '0'}',
                  style: TextStyle(fontSize: 14, color: AppTheme.textSecondary),
                ),
                const SizedBox(width: 16),
                const Icon(Icons.visibility,
                    size: 16, color: AppTheme.textSecondary),
                const SizedBox(width: 4),
                Text(
                  '${repo.watchers ?? '0'}',
                  style: TextStyle(fontSize: 14, color: AppTheme.textSecondary),
                ),
                const SizedBox(width: 16),
                if (repo.language != null) ...[
                  Container(
                    width: 12,
                    height: 12,
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.circular(6),
                    ),
                  ),
                  const SizedBox(width: 4),
                  Text(
                    repo.language!,
                    style:
                        TextStyle(fontSize: 14, color: AppTheme.textSecondary),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _refresh() async {
    // 重置状态并重新加载数据
    setState(() {
      _currentPage = 1;
      _hasMore = true;
      _repositories = [];
    });
    await _loadRepositories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('仓库'),
        elevation: 4,
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: _isLoading && _currentPage == 1
            ? const Center(child: CircularProgressIndicator())
            : _errorMessage != null
                ? ListView(
                    children: [
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.all(32),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Icon(Icons.error_outline,
                                  size: 48, color: AppTheme.errorColor),
                              const SizedBox(height: 16),
                              Text(
                                _errorMessage!,
                                textAlign: TextAlign.center,
                                style: TextStyle(color: AppTheme.textSecondary),
                              ),
                              const SizedBox(height: 16),
                              ElevatedButton(
                                onPressed: _refresh,
                                child: const Text('重试'),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                : _repositories.isEmpty
                    ? ListView(
                        children: [
                          Center(
                            child: Padding(
                              padding: const EdgeInsets.all(32),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(Icons.code_off,
                                      size: 48, color: AppTheme.textSecondary),
                                  const SizedBox(height: 16),
                                  Text(
                                    '暂无仓库数据',
                                    style: TextStyle(
                                        color: AppTheme.textSecondary),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      )
                    : NotificationListener<ScrollNotification>(
                        onNotification: (notification) {
                          if (notification is ScrollEndNotification &&
                              notification.metrics.extentAfter == 0 &&
                              _hasMore &&
                              !_isLoading) {
                            _loadRepositories();
                          }
                          return true;
                        },
                        child: ListView.builder(
                          itemCount: _repositories.length + (_hasMore ? 1 : 0),
                          itemBuilder: (context, index) {
                            if (index == _repositories.length) {
                              return _isLoading
                                  ? const Center(
                                      child: CircularProgressIndicator())
                                  : const SizedBox();
                            }
                            return _buildRepositoryItem(_repositories[index]);
                          },
                        ),
                      ),
      ),
    );
  }
}
